package com.india.project.push.server;

import com.india.common.threads.ThreadPool;
import com.india.project.push.cachedata.CacheData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MyApplicationRunner {
    private static List<WmsToOtcConsumerServer> wms_threadList = new ArrayList<>();
    private static final Logger log = LoggerFactory.getLogger(MyApplicationRunner.class);
    private ThreadPool threadPool;
    private int wmsThreadSize = 1;// 推送默认线程个数1

    public MyApplicationRunner() {
        threadPool = ThreadPool.getInstanceByParams(
                50, 100, 0L, "SECONDS",
                3000, "DISCARDPOLICY");
    }

    public void startThread() {
        // 启动业务消费处理线程进行转发数据
        for (int i = 0; i < wmsThreadSize; i++) {
            WmsToOtcConsumerServer wmsThread = new WmsToOtcConsumerServer();
            wmsThread.setRunFlag(true);
            wmsThread.setThreadNum(i);
            threadPool.executeThread(wmsThread);
            wms_threadList.add(wmsThread);
        }
        MonitorThread();
    }

    public void MonitorThread() {
        while (true) {
            try {
                Thread.sleep(1000 * 30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int wmsToOtcQueSize = CacheData.wms_msg_que.size();
            log.info("当前队列长度    =======》    " + wmsToOtcQueSize + " 线程个数    =======》    " + wms_threadList.size());
            if (wmsToOtcQueSize > 300) {
                for (int i = 1; i <= 100; i++) {
                    WmsToOtcConsumerServer wmsThread = new WmsToOtcConsumerServer();
                    wmsThread.setRunFlag(true);
                    wmsThread.setThreadNum(wms_threadList.size() + i);
                    threadPool.executeThread(wmsThread);
                    wms_threadList.add(wmsThread);
                }
            } else {
                // 关闭多余的消费者
                int i = 0;
                Iterator<WmsToOtcConsumerServer> consumerServerIterator = wms_threadList.iterator();
                while (consumerServerIterator.hasNext()) {
                    WmsToOtcConsumerServer consumerServer = consumerServerIterator.next();
                    if (wms_threadList.size() > wmsThreadSize) {
                        consumerServer.setRunFlag(false);
                        consumerServerIterator.remove();
                    } else {
                        consumerServer.setThreadNum(i);
                        i++;
                    }
                }
            }
        }
    }
}
